<template>
  <div class="zs-table-page-container">
    <div class="zs-card-sm zs-space-bottom zs-layout-flex-row zs-layout-justify-between">
      <span>
        <el-select @change="projectChange" value-key="biProjectCode" v-model="queryParams.projectInfo" filterable
          class="zs-select-md zs-space-right-sm" placeholder="项目名称">
          <el-option v-for="item in projectList" :key="item.biProjectCode" :label="item.projectName"
            :value="item" />
        </el-select>
        <el-date-picker @change="queryList" class="zs-space-right-sm" v-model="queryParams.costTime" type="month"
          placeholder="日期" :clearable="false" value-format="YYYY-MM" :prefix-icon="DateBeforeIcon" />
        <el-button @click="queryList" class="zs-btn-plain">查询</el-button>
      </span>
      <span>
        <!-- v-btnPermi="{ permis: ['p_btn_budget_costdetails_subject_in_export'] }"> -->
        <el-button class="zs-btn-primary zs-btn-md" @click="handleDownload('export')">
          <el-icon class="el-icon--left">
            <Upload />
          </el-icon>导出
        </el-button>
      </span>
    </div>
    <div class="zs-card zs-table-page-content">
      <hsTableV2 
        isTree 
        :loading="tableData.loading" 
        :columns="tableData.columns" 
        :data="tableData.data"
        :expendList="tableData.defaultExpendList" 
        rowKey="courseNumber" 
        expandColumnKey="subjectNum" 
      />
      <div class="zs-text-gray-dark zs-text-sm zs-space-top">单位：万元</div>
    </div>
  </div>
  <DetailDrawer 
    :drawerTitle="detailInfo.title"
    v-model:isShow="detailInfo.isShow"
    :currentData="detailInfo.currentData"
    :isHotel="isHotel"
    :currentYear="year"
    :currentMonth="month"
  />
  <CostDetailDrawer 
    drawerTitle="经营依据"
    v-model:isShow="costDetailInfo.isShow"
    :currentData="costDetailInfo.currentData"
    :currentYear="year"
    :currentMonth="month"
  />
</template>

<script setup lang="jsx">
import DetailDrawer from './components/detail-drawer';
import CostDetailDrawer from './components/cost-detail-drawer';
import { downloadNewFile, listToTree, formatArea } from "@/utils/publicUtils"
import dbPublicApi from '@/api/dbPublic'
import detailPagesApi from '@/api/Manage/Business/detailPages'
import { reactive, ref, shallowRef, h, computed } from "vue"
import { useRoute } from "vue-router";

const DateBeforeIcon = shallowRef({
  render () {
    return h('span', { style: { 'font-size': '12px' } }, '截至')
  },
})


let { biProjectCode, projectCode, bizType, updateDate, tabPermi } = useRoute().query
let projectName = ref('')
let isHotel = ['HOTEL', 'APARTMENT'].includes(bizType)
// 查询条件
let queryParams = reactive({
  projectInfo:{biProjectCode, projectCode},
  biProjectCode,
  projectCode,
  costTime: '',
})

let year = computed(()=>queryParams.costTime.split('-')[0] || '')
let month = computed(()=>queryParams.costTime.split('-')[1] || '')

function projectChange(val) {
  projectName.value = val.projectName
  queryParams.biProjectCode = val.biProjectCode
  queryParams.projectCode = val.projectCode
  queryList()
}

// 表格数据
let dictObj = {
  1: { dictLabel: '合格', dictValue: 1 },
  2: { dictLabel: '不合格', dictValue: 2 },
  3: { dictLabel: '改进', dictValue: 3 },
}
let tableData = reactive({
  loading:false,
  data:[],
  columns:[
    { key: 'subjectNum', align: "left", title: '科目编码', width: 150, minWidth: 150, },
    { key: 'courseName', align: "left", title: '科目', width: 200, minWidth: 200, indentKey: "level" },
    { key: 'ysCost', align: "right", title: '预算', flexGrow:2, cellRenderer:({rowData},empty)=>rowRender(rowData, empty, 'ysCost', 'integer') },
    { key: 'jyCost', align: "right", title: '经营依据', flexGrow:2, cellRenderer:({rowData},empty)=>rowRender(rowData, empty, 'jyCost', 'integer', true)  },
    { key: 'sjCost', align: "right", title: '实际', flexGrow:2, cellRenderer:({rowData},empty)=>rowRender(rowData, empty, 'sjCost', 'integer') },
    { key: 'ysProportion', align: "right", title: '预算比例', flexGrow:1, cellRenderer:({rowData},empty)=>rowRender(rowData, empty, 'ysProportion', 'percentage') },
    { key: 'sjProportion', align: "right", title: '实际比例', flexGrow:1, cellRenderer:({rowData},empty)=>rowRender(rowData, empty, 'sjProportion', 'percentage') },
    { key: 'dcProportion', align: "right", title: '达成率', flexGrow:1, cellRenderer:({rowData},empty)=>rowRender(rowData, empty, 'dcProportion', 'percentage') },
    { key: 'conclusion', align: "right", title: '对标结论', flexGrow:1, cellRenderer:({rowData},empty)=>rowRender(rowData, empty, 'conclusion', 'dict') },
  ],
  defaultExpendList:[]
})

if (['COMMERCIAL','OFFICE','INDUSTRIAL'].includes(bizType)) {
  tableData.columns.splice(5, 2)
}


let fixedClickSubjectCode = ['2.2.1','2.2.2']
function rowRender(row, empty, key, type, flg) {
  if (!row[key] && row[key] !== 0) return empty
  let sigin = isHotel ? '%' : '率'
  if (row.courseName.indexOf(sigin) > -1 || type == 'percentage') {
    return key == 'dcProportion' ?  <ElTooltip content={String(row[key])} placement="top">
        <span>{ Math.round(row[key]) + '%' }</span>
      </ElTooltip> : (formatArea(row[key], 2) + '%')
  } else if(type == 'integer'){
    let curVal = formatArea(Math.round(row[key] / 10000) , 0)
    let yuanVal = formatArea(row[key], 2)
    let curFlg = (flg && row.lastStage == 1 && row.parentNumber !== '0') || (!isHotel && fixedClickSubjectCode.includes(row.courseNumber) && flg) 
    let type = fixedClickSubjectCode.includes(row.parentNumber) ? 'children' : 'parent'
    // let curFlg = (flg && row.lastStage == 1 && row.parentNumber !== '0') || (!isHotel && row.courseNumber == '2.2.1' && key == 'sjCost')
    if (curFlg) {
      return <ElTooltip content={yuanVal} placement="top">
        <el-button class="zs-link" link size="small" onClick={()=>openDetailDrawer(row,type)}>{ curVal }</el-button>
      </ElTooltip>
    } else {
      return <ElTooltip content={yuanVal} placement="top">
        <span>{ curVal }</span>
      </ElTooltip>
    }
  } else if(type == 'dict') {
    let curLabel = dictObj[row[key]]?.dictLabel || empty
    return <span class={{'zs-text-red':row[key] == 2,'zs-text-green':row[key] == 1,'zs-text-orange':row[key] == 3}}>{curLabel}</span>
  }
}

let detailInfo = reactive({
  isShow:false,
  title:'经营依据',
  currentData:{}
})

let costDetailInfo = reactive({
  isShow:false,
  title:'经营依据',
  currentData:{}
})

async function openDetailDrawer(row, curType) {
  let { courseNumber, courseName, type, parentNumber } = row
  let params = {}
  let res = null
  if (isHotel) {
    params = Object.assign({courseNumber}, queryParams)
    res = await detailPagesApi.costAnalysisHotelDetailApi(params).then(res=>res)
  } else {
    params = {courseNumber, bizType, parentNumber, year:year.value, month:month.value, biProjectCode: queryParams.biProjectCode}
    res = await detailPagesApi.costAnalysisBusinessDetailApi(params).then(res=>res)
  }
  let resData = res.data
  let curRowData = { courseNumber, courseName, type, projectCode: queryParams.projectCode, currentYear: queryParams.costTime.split('-')[0], parentNumber }
  if (curType == 'children') {
    costDetailInfo.isShow = true
    costDetailInfo.currentData = Object.assign(curRowData,resData.data.list[0] || {})
    return
  }
  detailInfo.isShow = true
  if(resData.code == 200){
    resData.data.list = resData.data.list.map((el,index)=>{ return { name: el.title,id: `detail-drawer-params${index+1}`, ...el } })
    let curData = Object.assign(curRowData,resData.data)
    detailInfo.currentData = curData
  }
}


async function queryList () {
  tableData.loading = true
  let curData = null
  let expendList = []
  if (isHotel) {
    curData = await detailPagesApi.costAnalysisHotelListApi(queryParams).then(res=>res.data)
  } else {
    let params = Object.assign({bizType, year:year.value, month:month.value}, queryParams)
    curData = await detailPagesApi.costAnalysisBusinessListApi(params).then(res=>res.data)
  }
  if (curData.code == 200) {
    tableData.data = listToTree(curData.data, 'parentNumber', 'courseNumber', null, (item) =>{
      if (item.parentNumber == '2.1') item.type = 'fixed'
      if (item.parentNumber == '2.2') item.type = 'change'
      if (item.lastStage !== 1) expendList.push(item.courseNumber)
    })
    tableData.defaultExpendList = expendList
  } else {
    tableData.data = []
  }
  tableData.loading = false
}

// 导出
async function handleDownload() {
  let fileName = `${decodeURI(projectName.value)}_${queryParams.costTime}_费控分析明细.xls`
  let fileData
  if (isHotel) {
    await detailPagesApi.exportCostAnalysisHotelListApi(queryParams).then(res => {
      fileData = res.data
    })
  } else {
    let params = {bizType, year:year.value, month:month.value, biProjectCode: queryParams.biProjectCode}
    await detailPagesApi.exportCostAnalysisBusinessListApi(params).then(res => {
      fileData = res.data
    })
  }
  downloadNewFile(fileData, fileName)
}

// function getUpdateTime() {
//   queryUpdateTimeApi().then(res=>{
//     let resData = res.data
//     if(resData.code == 200){
//       queryParams.costTime = resData.data;
//       queryList()
//     }
//   })
// }
// getUpdateTime()

// 项目下拉选
let projectList = ref([])
const getPorjectList = () => {
  dbPublicApi.queryProjectPcApi({ dataTime: updateDate, resourceKey: tabPermi }).then((res) => {
    if (res.data.code == 200) {
      projectList.value = res.data.data
      projectName.value = projectList.value.filter(el=> el.biProjectCode == queryParams.biProjectCode)[0].projectName
    }
  })
}
getPorjectList()

function queryUpdate() {
  dbPublicApi.queryMonthsTimeApi().then(res=>{
    let resData = res.data
    if(resData.code == 200){
      queryParams.costTime = resData.data;
      queryList()
    }
  }) 
}
queryUpdate()
</script>

<style lang="scss" scoped>
:deep(.el-table-v2){
  .el-button{
    padding: 0;
    font-size: 13px;
    font-family: PingFangSC, PingFangSC-Regular, Arial, sans-serif;
  }
}
</style>